/*
 * Copyright 2009 Cedric Priscal
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License. 
 */

package com.vanzo.talkie2;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.os.Handler;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ScrollView;
import android.widget.TextView;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.InvalidParameterException;

import android_serialport_api.SerialPort;

public class SerialPortActivity extends Activity {

    private static final String TAG = "SerialPortActivity";

    protected Application mApplication;
    protected SerialPort mSerialPort;
    protected OutputStream mOutputStream;
    private InputStream mInputStream;
    private ReadThread mReadThread;


    private TextView console;
    private Button send, correct, error;
    private ScrollView scrollView;
    private int count = 0;


    private class ReadThread extends Thread {

        @Override
        public void run() {
            super.run();
            while (!isInterrupted()) {
                int size;
                try {
                    byte[] buffer = new byte[128];
                    if (mInputStream == null) return;
                    size = mInputStream.read(buffer);
                    if (size > 0) {
                        Log.d("zts", "size = " + size);
                        onDataReceived(buffer, size);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    return;
                }
            }
        }
    }

    ForegroundColorSpan colorSpan;
    SpannableString spannableString;

    private void DisplayError(int resourceId) {
        AlertDialog.Builder b = new AlertDialog.Builder(this);
        b.setTitle("Error");
        b.setMessage(resourceId);
        b.setPositiveButton("OK", new OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                SerialPortActivity.this.finish();
            }
        });
        b.show();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        init();
        setContentView(R.layout.activity_serial_port);
        findViewSetListener();
        startSendAt();
    }

    private void startSendAt() {
        handler.postDelayed(runnable, 2000);
    }

    private void findViewSetListener() {
        scrollView = (ScrollView) findViewById(R.id.scroll_view);
        console = (TextView) findViewById(R.id.console);
        send = (Button) findViewById(R.id.send);
        correct = (Button) findViewById(R.id.correct_button);
        error = (Button) findViewById(R.id.error_button);

        correct.setEnabled(false);

        send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendAt();
            }
        });
        correct.setOnClickListener(resultClickListener);
        error.setOnClickListener(resultClickListener);
    }

    private void sendAt() {
        int i;
//        CharSequence t = "AT+DMOCONNECT\r";
        CharSequence t = "$CCICA,0,00*7B\r\n";
        char[] text = new char[t.length()];
//                send.setEnabled(false);
        for (i = 0; i < t.length(); i++) {
            text[i] = t.charAt(i);
        }
        try {
            console.append("\n" + getString(R.string.emission) + "\n" + t);
            mOutputStream.write(new String(text).getBytes());
            mOutputStream.write('\n');
            count++;
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    protected void init() {
        colorSpan = new ForegroundColorSpan(getResources().getColor(R.color.text_span_color));
        spannableString = new SpannableString(getString(R.string.test_success));
        spannableString.setSpan(colorSpan, 0, getString(R.string.test_success).length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        mApplication = (Application) getApplication();
        try {
            mSerialPort = mApplication.getSerialPort("dev/ttyMT1",115200);
            mOutputStream = mSerialPort.getOutputStream();
            mInputStream = mSerialPort.getInputStream();

			/* Create a receiving thread */
            mReadThread = new ReadThread();
            mReadThread.start();
        } catch (SecurityException e) {
            DisplayError(R.string.error_security);
        } catch (IOException e) {
            DisplayError(R.string.error_unknown);
        } catch (InvalidParameterException e) {
            DisplayError(R.string.error_configuration);
        }
    }

    private StringBuilder temp = new StringBuilder();

    protected void onDataReceived(final byte[] buffer, final int size) {
        runOnUiThread(new Runnable() {
            public void run() {
                temp.append(new String(buffer, 0, size));
                Log.d("zts", temp.toString());
                if (temp.toString().endsWith("\r\n")) {
                    if (console != null) {
                        console.append("\n" + getString(R.string.receive) + temp);
//                        console.append(spannableString);
                        console.append(getString(R.string.test_success));
                    }
                    if (temp.toString().contains("+DMOCONNECT")) {
                        correct.setEnabled(true);
                    }
                    temp = new StringBuilder();
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            scrollView.fullScroll(ScrollView.FOCUS_DOWN);
                        }
                    });
                } else {

                }
            }
        });
    }


    private Handler handler = new Handler();

    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            if (count < 3) {
                sendAt();
                handler.postDelayed(this, 2000);
            } else {
                handler.removeCallbacks(runnable);
            }
        }
    };


    @Override
    protected void onDestroy() {
        if (mReadThread != null)
            mReadThread.interrupt();
        mApplication.closeSerialPort();
        mSerialPort = null;
        super.onDestroy();
    }

    View.OnClickListener resultClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.correct_button:
                    SerialPortActivity.this.setResult(0);
                    finish();
                    break;
                case R.id.error_button:
                    SerialPortActivity.this.setResult(-1);
                    finish();
                    break;
            }
        }
    };

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return keyCode == KeyEvent.KEYCODE_BACK || super.onKeyDown(keyCode, event);
    }
}
